<template>
  <div class="list-table">
    <div class="area-header">
      <span class="area-header-title">{{ $t('首页模板') }}</span>
    </div>
    <el-form ref="queryForm" :model="queryParams" :inline="true" @submit.native.prevent>
      <el-form-item :label="$t('模板名称')" prop="name">
        <el-input v-model="queryParams.name" clearable :placeholder="$t('模板名称')" @keyup.enter.native="queryHandle" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="queryHandle">{{ $t("搜索") }}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("重置") }}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:hometemplate:edit']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="addHandle"
        >{{ $t("新增") }}</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          v-hasPermi="['system:hometemplate:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="exportHandle"
        >{{ $t("导出") }}</el-button>
      </el-col>-->
    </el-row>

    <el-table v-loading="loading" :data="homeTemplateList" border>
      <el-table-column :label="$t('序号')" type="index" align="center" show-overflow-tooltip width="50">
        <template slot-scope="scope">
          {{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('模板名称')" align="center" prop="name">
        <template slot-scope="scope">
          <el-link type="primary" @click="updateHandle(scope.row)">{{ scope.row.name }}</el-link>
        </template>
      </el-table-column>
      <el-table-column :label="$t('操作')" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:hometemplate:edit']"
            size="small"
            type="text"
            icon="el-icon-edit"
            @click="updateHandle(scope.row)"
          >{{ $t('修改') }}</el-button>
          <el-button
            v-hasPermi="['system:hometemplate:allot']"
            size="mini"
            type="text"
            icon="el-icon-magic-stick"
            @click="handleUserScope(scope.row)"
          >{{ $t("分配") }}</el-button>
          <el-button
            v-hasPermi="['system:hometemplate:remove']"
            size="small"
            type="text"
            icon="el-icon-delete"
            @click="deleteHandle(scope.row)"
          >{{ $t('删除') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 分配 -->
    <el-dialog :title="$t('用户角色')" :visible.sync="openUserScope" width="50%" :close-on-click-modal="false" :lock-scroll="false" append-to-body @close="cancelUserScope">
      <el-transfer ref="transfer" v-model="toData" v-loading="userScopeLoading" :data="formData" filterable :titles="[$t('未选择用户'), $t('已选择用户')]" :filter-method="filterMethod" :filter-placeholder="$t('支持昵称、名称、部门搜索')" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUserScope">{{ $t("确定") }}</el-button>
        <el-button @click="cancelUserScope">{{ $t("取消") }}</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改首页模板对话框 -->
    <el-dialog :title="$t('首页模板')" width="800px" :visible.sync="formOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <homeTemplateForm ref="homeTemplateForm" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listHomeTemplate,
  delHomeTemplate,
  exportHomeTemplate,
  saveUserTemplate, findByTemplateId
} from '@/api/system/home/template/homeTemplate'
import homeTemplateForm from './homeTemplateForm.vue'
import { allUser } from '@/api/system/user'
export default {
    components: {
        homeTemplateForm
    },
  data() {
      return {
          // 遮罩层
          loading: true,
          // 是否显示弹出层(分配用户角色)
          openUserScope: false,
          // 遮罩层(分配用户角色)
          userScopeLoading: false,
          // 用户数组
          formData: [],
          toData: [],
          // 总条数
          total: 0,
          // 首页模板表格数据
          homeTemplateList: [],
          // 弹出层标题
          title: '',
          // 是否显示弹出层
          formOpen: false,
          // 查询参数
          queryParams: {
              name: undefined,
              pageNum: 1,
              pageSize: 10
          },
          // 表单参数
          form: {},
          // 表单校验
          rules: {}
      }
  },
  created() {
      this.getList()
  },
  methods: {
    /** 查询首页模板列表 */
    getList() {
        this.loading = true
        listHomeTemplate(this.queryParams).then(response => {
            this.homeTemplateList = response.rows
            this.total = response.total
            this.loading = false
        })
    },

    // 表单重置
    reset() {
        this.form = {
            id: undefined,
            name: undefined,
            remark: undefined,
            createBy: undefined,
            createTime: undefined,
            updateBy: undefined,
            updateTime: undefined,
            delFlag: undefined
        }
        this.resetForm('form')
    },
    /** 搜索按钮操作 */
    queryHandle() {
        this.queryParams.pageNum = 1
        this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
        this.resetForm('queryForm')
        this.queryHandle()
    },
    /** 新增按钮操作 */
    addHandle() {
        this.formOpen = true
        this.title = '添加首页模板'
        this.$nextTick(() => {
            this.$refs.homeTemplateForm.init(null)
        })
    },
    /** 修改按钮操作 */
    updateHandle(row) {
        this.formOpen = true
        this.title = '修改首页模板'
        this.$nextTick(() => {
            // 调用form页面的 init 方法初始化数据
            this.$refs.homeTemplateForm.init(row)
        })
    },
    /** 删除按钮操作 */
    deleteHandle(row) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return delHomeTemplate(row.id)
        }).then(() => {
            this.getList()
            this.msgSuccess(this.$t('删除成功'))
        }).catch(function() {
        })
    },
    /** 导出按钮操作 */
    exportHandle() {
        const queryParams = this.queryParams
        this.$confirm(this.$t('是否确认导出?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
        }).then(function() {
            return exportHomeTemplate(queryParams)
        }).then(response => {
            this.download(response.msg)
        }).catch(function() {
        })
    },
    // 分配用户角色操作
    async handleUserScope(row) {
      this.userScopeLoading = true
      await findByTemplateId(row.id).then(response => {
        this.toData = response.data
      })
       allUser().then(response => {
        response.data.map((item) => {
          const index = this.toData.indexOf(item.id)
          const data = {
            key: item.id,
            label: item.nickName + ' / ' + `${item.userName}` + ' / ' + `${item.dept.deptName}`,
            pinyin: item.userName,
            disabled: item.id === this.toData[index]
          }
          this.formData.push(data)
        })
        this.userScopeLoading = false
      })
      this.form.templateId = row.id
      this.openUserScope = true
    },
    // 提交用户角色分配
    submitUserScope() {
      const data = {
        ids: this.toData,
        templateId: this.form.templateId
      }
      saveUserTemplate(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t('保存成功'))
          this.formData = []
          this.toData = []
          this.openUserScope = false
          this.getList()
        } else {
          this.msgError(response.msg)
        }
      })
    },
    // 分配用户搜索
    filterMethod(query, item) {
      return item.pinyin.indexOf(query) > -1 || item.label.indexOf(query) > -1
    },
    // 分配用户角色 关闭按钮
    cancelUserScope() {
      this.openUserScope = false
      this.formData = []
      this.toData = []
      this.$refs.transfer.clearQuery('left')
      this.$refs.transfer.clearQuery('right')
    }
    // changeUserScope(value, direction, movedKeys) {
    //   if (direction === 'left') {
    //     selectLastRole(movedKeys).then(response => {
    //       response.data.map((item) => {
    //         this.toData.push(item)
    //       })
    //       if (response.data.length > 0) {
    //         this.msgError(this.$t('只有一个模板的用户不可取消分配该角色'))
    //       }
    //     })
    //   }
    // }
  }
}
</script>
